package com.xichen.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xichen.dao.UserMapper;
import com.xichen.entity.PageResult;
import com.xichen.entity.QueryPageBean;
import com.xichen.pojo.User;
import com.xichen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tang wei
 * @version 1.0
 * @date 2020/7/16 13:48
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 通过用户名查询用户信息
     * @param loginName
     * @return
     */
    @Override
    public User findUserByLoginName(String loginName) {
        //添加查询条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName",loginName);
        //通过此条件查询用户信息
        User user = userMapper.selectOneByExample(example);
        return user;
    }

    /**
     * 分页查询用户
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findUserPage(QueryPageBean queryPageBean) {
        //从查询条件对象中获取当前页
        Integer currentPage = queryPageBean.getCurrentPage();
        //从查询条件对象中获取每页存放数量
        Integer pageSize = queryPageBean.getPageSize();
        //获取查询条件中的用户名查询
        String queryUsername = queryPageBean.getQueryUsername();
        //获取查询条件中的手机号查询
        String queryTel = queryPageBean.getQueryTel();
        //分页插件
        PageHelper.startPage(currentPage,pageSize);
        //查询结果封装在Page中
        Page<User> page = userMapper.findByCondition(queryUsername,queryTel);
        //返回分页查询结果
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        userMapper.insert(user);
    }

    /**
     * 通过id查找用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /***
     * 通过名称查找用户，且不等于此id
     * @param loginName
     * @param id
     * @return
     */
    @Override
    public User findUserByLoginNameAndNotEqualId(String loginName, Long id) {
        return userMapper.findUserByLoginNameAndNotEqualId(loginName,id);

    }

    /**
     *
     * @param user
     */
    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    /**
     * 根据id删除用户
     * @param id
     */
    @Override
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }
}
